package com.video.user.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.video.common.enumeration.AppHttpCodeEnum;
import com.video.common.result.ResponseResult;
import com.video.user.config.JwtProperties;
import com.video.user.domain.dto.LoginDto;
import com.video.user.domain.entity.AppUser;
import com.video.user.mapper.AppUserMapper;
import com.video.user.service.IAppUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.video.user.utils.JwtTool;

/**
 * <p>
 * app用户表 服务实现类
 * </p>
 *
 * @author la
 * @since 2024-11-04
 */
@Service
@RequiredArgsConstructor
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {

    // 导入token生成工具
    private final JwtTool jwtTool;


    private final JwtProperties jwtProperties;

    /*
     * 登录接口
     * */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();

        // 查询数据库,判断是否有用户
        AppUser user = lambdaQuery()
                .eq(username != null, AppUser::getUsername, username)
                .one();

        // 判断用户是否存在
        if (user == null) {
            return ResponseResult.errorResult(987, "没有找到用户");
        }

        // 判断密码
        if (!DigestUtil.md5Hex(password).equals(user.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PASSWORD_ERROR);
        }

        // 生成token
        String token = jwtTool.createToken(user.getId(), jwtProperties.getTokenTTL());

        return ResponseResult.okResult(token);
    }

    /*
     * 更新用户信息
     * */
    @Override
    public void updateUser(AppUser user) {
        user.setUpdateTime(System.currentTimeMillis());
        updateById(user);
    }
}
